﻿/*
* 创建者：LIYINFAI
* 创建时间：2023/10/15 11:40:00
* 描述：
* --------------------------------------
* 修改说明：
* --------------------------------------
*/
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;

namespace CommonLibrary
{
    /// <summary>
    /// 天平串口配置
    /// </summary>
    public class GagfComParam : ComParameter
    {
        /// <summary>
        /// 触发清零地址
        /// </summary>
        [Description("触发清零地址")]
        [JsonProperty(PropertyName = "triggerZeroAddress")]
        public string TriggerZeroAddress { get; set; } = string.Empty;
        /// <summary>
        /// 触发重量地址
        /// </summary>
        [Description("触发重量地址")]
        [JsonProperty(PropertyName = "triggerAddress")]
        public string TriggerAddress { get; set; } = string.Empty;
        /// <summary>
        /// 结果地址
        /// </summary>
        [Description("结果地址")]
        [JsonProperty(PropertyName = "resultAddress")]
        public string ResultAddress { get; set; } = string.Empty;
        /// <summary>
        /// 称重完成地址
        /// </summary>
        [Description("称重完成地址")]
        [JsonProperty(PropertyName = "resultDoneAddress")]
        public string ResultDoneAddress { get; set; } = string.Empty;
        /// <summary>
        /// 清零完成地址
        /// </summary>
        [Description("清零完成地址")]
        [JsonProperty(PropertyName = "zeroDoneAddress")]
        public string ZeroDoneAddress { get; set; } = string.Empty;
        /// <summary>
        /// 描述信息
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return CommonHelper.GetObjectString(this);
        }
    }

    /// <summary>
    /// 天平TCP配置
    /// </summary>
    public class GagfTcpParam : TcpParameter
    {
        /// <summary>
        /// 触发清零地址
        /// </summary>
        [Description("触发清零地址")]
        [JsonProperty(PropertyName = "triggerZeroAddress")]
        public string TriggerZeroAddress { get; set; } = string.Empty;
        /// <summary>
        /// 触发重量地址
        /// </summary>
        [Description("触发重量地址")]
        [JsonProperty(PropertyName = "triggerAddress")]
        public string TriggerAddress { get; set; } = string.Empty;
        /// <summary>
        /// 重量结果地址
        /// </summary>
        [Description("重量结果地址")]
        [JsonProperty(PropertyName = "resultAddress")]
        public string ResultAddress { get; set; } = string.Empty;
        /// <summary>
        /// 重量完成地址
        /// </summary>
        [Description("重量完成地址")]
        [JsonProperty(PropertyName = "resultDoneAddress")]
        public string ResultDoneAddress { get; set; } = string.Empty;
        /// <summary>
        /// 清零完成地址
        /// </summary>
        [Description("清零完成地址")]
        [JsonProperty(PropertyName = "zeroDoneAddress")]
        public string ZeroDoneAddress { get; set; } = string.Empty;
        /// <summary>
        /// 描述信息
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return CommonHelper.GetObjectString(this);
        }
    }
    /// <summary>
    /// 天平帮助类
    /// </summary>
    public class GagfHelper : BaseHelper
    {
        /// <summary>
        /// TCP配置文件
        /// </summary>
        static string autoTcpGagfConfigPath = Path.Combine(CommonHelper.COMMON_CONFIG_DIR, "GagfTCPConfig.json");
        /// <summary>
        /// 串口配置文件
        /// </summary>
        static string autoComGagfConfigPath = Path.Combine(CommonHelper.COMMON_CONFIG_DIR, "GagfComConfig.json");
        /// <summary>
        /// 获取串口配置文件内容
        /// </summary>
        /// <returns></returns>
        public static List<GagfComParam> GetAutoGagfComConfig()
        {
            return CommonHelper.GetJsonListFromFile<GagfComParam>(autoComGagfConfigPath);
        }
        /// <summary>
        /// 保存串口配置文件内容
        /// </summary>
        /// <param name="list"></param>
        public static void SaveAutoGagfComConfig(List<GagfComParam> list)
        {
            CommonHelper.SaveToJsonFile(list, autoComGagfConfigPath);
        }
        /// <summary>
        /// 获取TCP配置文件内容
        /// </summary>
        /// <returns></returns>
        public static List<GagfTcpParam> GetAutoGagfTcpConfig()
        {
            return CommonHelper.GetJsonListFromFile<GagfTcpParam>(autoTcpGagfConfigPath);
        }
        /// <summary>
        /// 保存TCP配置文件内容
        /// </summary>
        /// <param name="list"></param>
        public static void SaveAutoGagfTcpConfig(List<GagfTcpParam> list)
        {
            CommonHelper.SaveToJsonFile(list, autoTcpGagfConfigPath);
        }
        #region 每个Helper特定的参数
        /// <summary>
        /// 通讯超时时间，默认1000毫秒
        /// </summary>
        public override int CommunicationTimeout => BusinessConfig.Instance().GagfTimeout;
        private string ERROR_WEIGHT = "ERROR";
        /// <summary>
        /// 读取重量命令
        /// </summary>
        public readonly byte[] GetWeightCommand = new byte[] { 0x51, 0x0D, 0x0A };
        /// <summary>
        /// 清零命令
        /// </summary>
        public readonly byte[] RezeroCommand = new byte[] { 0x52, 0x0D, 0x0A };
        /// <summary>
        /// 读取重量命令（稳定重量）
        /// </summary>
        public readonly byte[] GetStableWeightCommand = new byte[] { 0x53, 0x0D, 0x0A };
        #endregion
        /// <summary>
        /// 称重后续
        /// </summary>
        /// <param name="weight"></param>
        /// <param name="entity"></param>
        private void BusinessGetWeightHandler(ref string weight, GagfWeightPLCEntity entity)
        {
            var param = new GAGFExcuteEntity()
            {
                Weight = weight,
                WeightPLCEntity = entity
            };
            param = CommonHelper.GetJson(PluginManager.Instance.Excute(this.Name, "GAGF_WEIGHT", CommonHelper.GetJsonString(param, Formatting.None)), param);
            weight = param.Weight;
        }
        /// <summary>
        /// 清零后续
        /// </summary>
        /// <param name="entity"></param>
        private void BusinessRezeroHandler(GagfRezeroPLCEntity entity)
        {
            var param = new GAGFExcuteEntity()
            {
                RezeroPLCEntity = entity
            };
            CommonHelper.GetJson(PluginManager.Instance.Excute(this.Name, "GAGF_REZERO", CommonHelper.GetJsonString(param, Formatting.None)), param);
        }
        private object READ_LOCK = new object();
        /// <summary>
        /// COM 清零
        /// </summary>
        /// <returns></returns>
        private bool GetComRezero()
        {
            lock (READ_LOCK)
            {
                bool result = true;
                if (this.IsConnected)
                {
                    try
                    {
                        this.SerialSendASCIIString(this.RezeroCommand);
                        bool isAck = BusinessConfig.Instance().GagfRezeroAck;
                        if (isAck)
                        {
                            result = false;
                            var rezero1 = this.GetReturnBuffer();
                            CommonHelper.ApplicationEvents();
                            var rezero2 = this.GetReturnBuffer();
                            if (rezero1 != null && rezero1[0] == 0x06 && rezero2 != null && rezero2[0] == 0x06)
                            {
                                result = true;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        result = false;
                        LogHelper.Error(ex);
                    }
                }
                return result;
            }
        }
        /// <summary>
        /// TCP 清零
        /// </summary>
        /// <returns></returns>
        private bool GetTcpRezero()
        {
            lock (READ_LOCK)
            {
                bool result = true;
                if (this.IsConnected)
                {
                    try
                    {
                        this.TcpSend(this.RezeroCommand);
                        bool isAck = BusinessConfig.Instance().GagfRezeroAck;
                        if (isAck)
                        {
                            result = false;
                            var rezero1 = this.TcpReceive();
                            CommonHelper.ApplicationEvents();
                            var rezero2 = this.TcpReceive();
                            if (rezero1 != null && rezero1[0] == 0x06 && rezero2 != null && rezero2[0] == 0x06)
                            {
                                result = true;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        result = false;
                        LogHelper.Error(ex);
                    }
                }
                return result;
            }
        }
        /// <summary>
        /// COM 重量
        /// </summary>
        /// <returns></returns>
        private string GetComWeight()
        {
            lock (READ_LOCK)
            {
                string weight = this.ERROR_WEIGHT;
                if (this.IsConnected)
                {
                    try
                    {
                        bool isQ = BusinessConfig.Instance().GagfIsQ;
                        this.SerialSendASCIIString(isQ ? this.GetWeightCommand : this.GetStableWeightCommand);
                        CommonHelper.ApplicationEvents();
                        weight = this.GetSerialReturnASCIIString();
                    }
                    catch (Exception ex)
                    {
                        weight = this.ERROR_WEIGHT;
                        LogHelper.Error(ex);
                    }
                }
                return weight;
            }
        }
        /// <summary>
        /// TCP 重量
        /// </summary>
        /// <returns></returns>
        private string GetTcpWeight()
        {
            lock (READ_LOCK)
            {
                string weight = this.ERROR_WEIGHT;
                if (this.IsConnected)
                {
                    try
                    {
                        bool isQ = BusinessConfig.Instance().GagfIsQ;
                        this.TcpSend(isQ ? this.GetWeightCommand : this.GetStableWeightCommand);
                        CommonHelper.ApplicationEvents();
                        weight = this.TcpReceiveString();
                    }
                    catch (Exception ex)
                    {
                        weight = this.ERROR_WEIGHT;
                        LogHelper.Error(ex);
                    }
                }
                return weight;
            }
        }
        /// <summary>
        /// 获取重量
        /// </summary>
        /// <returns></returns>
        public string GetWeight()
        {
            return this.CommunicationType == ECommunicationType.SERIAL ? GetComWeight() : GetTcpWeight();
        }
        /// <summary>
        /// 天平逻辑
        /// </summary>
        /// <param name="handlerName"></param>
        /// <param name="handlerType"></param>
        /// <param name="otherAddress"></param>
        /// <param name="otherData"></param>
        public override void RealHandler(string handlerName, EHandlerType handlerType, object otherAddress, object otherData)
        {
            string weight = ERROR_WEIGHT;
            if (this.IsConnected)
            {
                Stopwatch stopwatch = Stopwatch.StartNew();
                try
                {
                    if (handlerType.Equals(EHandlerType.GAGF_GETWEIGHT))
                    {
                        this.RealShowMessage($"【{this.Name}】{handlerName}");
                        weight = GetWeight();
                        float temp = 0f;
                        //发现称重为0，根据是否进行二次称重来处理
                        if (BusinessConfig.Instance().GagfWeight2 && !string.IsNullOrWhiteSpace(weight) && float.TryParse(CommonHelper.GetNumberFromString(weight), out temp) && temp == 0f)
                        {
                            weight = GetWeight();
                        }
                    }
                    else if (handlerType.Equals(EHandlerType.GAGF_REZERO))
                    {
                        this.RealShowMessage($"【{this.Name}】{handlerName}");
                        bool temp = this.CommunicationType == ECommunicationType.SERIAL ? GetComRezero() : GetTcpRezero();
                        LogHelper.Info($"【{this.Name}】 清零结果：{temp}");
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                }
                finally
                {
                    stopwatch.Stop();
                    if (handlerType.Equals(EHandlerType.GAGF_GETWEIGHT))
                    {
                        GagfWeightPLCEntity entity1 = otherAddress as GagfWeightPLCEntity;
                        BusinessGetWeightHandler(ref weight, entity1);
                        this.RealShowMessage($"【{this.Name}】称重，耗时：{stopwatch.ElapsedMilliseconds} 毫秒，结果：{weight} g。", true);
                    }
                    else if (handlerType.Equals(EHandlerType.GAGF_REZERO))
                    {
                        GagfRezeroPLCEntity entity2 = otherAddress as GagfRezeroPLCEntity;
                        BusinessRezeroHandler(entity2);
                        this.RealShowMessage($"【{this.Name}】清零，耗时：{stopwatch.ElapsedMilliseconds} 毫秒。", true);
                    }
                }
            }
        }
    }
}
